#参考 https://github.com/fmoo/python-varint/blob/master/varint.py

import math

MAX_VARINT_LENGTH = 9

def _byte(b):
    return bytes((b, ))


def encode(number):
    buf = b''
    first_8_bit = False
    if number > pow(2, 56):
        first_8_bit = True

    while True:
        if first_8_bit:
            towrite = number & 0xff
            number >>= 8
            first_8_bit = False
        else:
            towrite = number & 0x7f
            number >>= 7
        if not buf:
            buf = _byte(towrite)
        else:
            buf = _byte(towrite | 0x80) + buf
        if not number:
            break
    return buf


def decode_bytes(buf):
    '''
    big-endian，从前面的字节取出的bit排在高位，而从后面的字节取出的位在低位
    最高9位，使用9位时，第九段无0特征，8*7+8=64
    '''
    try:
        shift = 7
        result = 0
        count = 0
        for i in buf:
            if result:
                result <<= shift
            count += 1
            if count == 9:
                result <<= 1  # 第九段须多移一位
                result |= i
            else:
                result |= (i & 0x7f)
            if not (i & 0x80) or count >= 9:
                break

        return result, count
    except Exception as err:
        print('decode_bytes: \t', err)


def varint_lenth(value):
    '''
    计算varint值应占据的长度
    '''
    return math.ceil(value / 0x80)
